<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <template v-slot:before>
          工13条记录
        </template>
        <template v-slot:after>
          <el-button size="small" type="danger" @click="exportFn">
            导出
          </el-button>
          <el-button size="small" type="success" @click="$router.push('/employees/import')">
            导入
          </el-button>
          <el-button size="small" type="primary" @click="addFn">
            新增
          </el-button>
        </template>
      </PageTools>
      <el-card>
        <el-table :data="tableDate">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="{row}">
              <!-- imgerror,解决图片出错，在mian.js里面 -->
              <!-- // 解决图片出错
          // 自定义全局指令，解决图片出错问题
          // Vue.directive('自定义指令名',{
          //   inserted(el, binding){
          //     el: 调用该指令的DOM元素
          //     binding.value: 使用指令时传入的值
          //   }
          // }) -->
              <img v-imgerror="require('../../assets/common/bigUserHeader.png')" :src="row.staffPhoto" style="width:50px" alt="">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用方式" prop="formOfEmployment" :formatter="formatDmployment" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template v-slot="{row}">
              <span>{{ row.timeOfEntry |formatDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="enableState">
            <template v-slot="{row}">
              <el-switch
                :value="row.enableState===1"
                active-color="#13ce66"
                inactive-color="#666"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="text" @click="toDetali(row.id)">查看</el-button>
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button type="text" @click="assignRoleRn(row.id)">角色</el-button>
              <el-button type="text" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center">
          <el-pagination layout="total,prev,pager,next" :page-size="size" :total="total" @current-change="currentChange" />
        </el-row>

      </el-card>
      <AddEmployee :show-dialog="showDialog" @closeEvent="showDialog=false" @addEvent="getEmployeesList" />
      <AssignRole ref="assignRole" :show-dialog.sync="visibleDialog" />
    </div>
  </div>
</template>

<script>
import employees from '../../api/constant/employees'
import { getEmployeesList, deleteEmployees } from '../../api/employee'
import AddEmployee from './compnent/add-employee.vue'
import { export_json_to_excel } from '../../vendor/Export2Excel'
import { formatDate } from '../../fliters/index'
import AssignRole from './compnent/assing-role.vue'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      tableDate: [],
      total: 50,
      size: 5,
      page: 1,
      showDialog: false,
      visibleDialog: false
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    // 角色分配
    assignRoleRn(id) {
      console.log(id)
      this.visibleDialog = true
      console.log(this.$refs.assignRole)
      this.$refs.assignRole.curId = id
      this.$refs.assignRole.getEmployeesDetail()
    },
    toDetali(id) {
      this.$router.push('/employees/detail/' + id)
    },
    async  exportFn() {
      const res = await getEmployeesList({
        // this是调用方法 getEmployeesList是一个接口
        page: 1,
        size: this.total
      })
      const result = res.rows.map(item => {
        return this.objToArr(item)
      })
      console.log('result: ', result)
      const header = ['手机号', '姓名', '入职日期', '转正日期', '工号']
      // const data = [
      //   ['13111111111', '小明', '2022-02-02', '2022-06-09', '8455'],
      //   ['13111111112', '小明', '2022-02-02', '2022-06-09', '8456'],
      //   ['13111111113', '小明', '2022-02-02', '2022-06-09', '8454']
      // ]
      export_json_to_excel({
        header,
        data: result
      })
    },
    objToArr(item) {
      const arr = []
      const user = {
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'correctionTime': '转正日期',
        'workNumber': '工号'
      }
      for (const key in user) {
        // 格式化文件时间，判断如果条件符合的时候就调用格式化的函数
        if (key === 'timeOfEntry' || key === 'correctionTime') {
          arr.push(formatDate(item[key], 'yyyy/MM/dd'))
        } else {
          arr.push(item[key])
        }
      }
      return arr
    },

    delFn(id) {
      this.$confirm('你确定删除吗', '提示', { type: 'warning'

      }).then(async() => {
        await deleteEmployees(id)
        // 解决删除最后一页的最后一天会空白bug
        if (this.tableDate.length === 1 && this.page !== 1) {
          this.page--
        }
        this.getEmployeesList()
      }).catch(err => {
        console.log('取消', err)
      })
    },
    addFn() {
      this.showDialog = true
    },
    // 格式化聘用形式
    formatDmployment(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // row: 表示当前行的数据对象
      // column：包含当前列表相关信息的对象
      // cellValue: 当前列属性对应的值
      // index：下标值
      // 函数返回什么内容，表格中就显示什么内容
      const obj = employees.hireType.find(item => Number(item.id) === Number(cellValue))
      return obj && obj.value || '未知'
    },
    currentChange(page) {
      this.page = page
      this.getEmployeesList()
    },
    async  getEmployeesList() {
      const res = await getEmployeesList({
        page: this.page,
        size: this.size
      })
      console.log('res: ', res)
      this.tableDate = res.rows
      this.total = res.total
    }
  }
}
</script>

<style>

</style>
